package Options::UserSync::API::UserDataUpdate;

use strict;
use DE_EPAGES::Core::API::Error qw (Error );
use DE_EPAGES::Trigger::API::Trigger qw ( TriggerHook );
use DE_EPAGES::Core::API::Log qw (LogDebug GetLog);
use DE_EPAGES::Object::API::Factory qw( LoadObject ExistsObjectByPath LoadObjectByPath Transaction DeleteObject );
use DE_EPAGES::Order::API::LineItemContainer qw(SaveShipping);
use DE_EPAGES::Object::API::Object::Object qw(clone insertChild);
use Data::Dumper;

use Options::Attributes::API::InterfaceCustomerGet;
use Options::Attributes::API::InterfaceCustomerUpdate;
use Options::UserSync::API::AddressFieldsConverter;

sub OBJAfterUpdateAddress {
                my ($hParams) = @_;
                my $CurrentAddress = $hParams->{'Object'};
                my $Path = $CurrentAddress->get('Path');
                # GetLog->error("OBJAfterUpdateAddress - TRIGERED" . Dumper($CurrentAddress));

         #       if (!ExistsObjectByPath($Path)) {
                   # this happens in MBO in the Customers->General->Address tab update.
         #       } else {
                if($Path =~ m/Orders/ || $Path =~ m/Customers/) {
                        #-------
                        # We are ignoring this hook when trigered during order placing.
                        # or in Customer context.
                        #-------
                } else {
                        #-------
                        # Making sync with Options
                        #-------
                GetLog->debug("OBJAfterUpdateAddressX - TRIGERED: " . $Path);
                GetLog->debug("OBJAfterUpdateAddressX- OBJ ID: " . $CurrentAddress->get('ID'));
                my $BFLastSyncTimestamp = $CurrentAddress->get('BFLastSyncTimestamp');
               # $BFLastSyncTimestamp  = $BFLastSyncTimestamp -3;
                my $timest = time;
                GetLog->debug("  $timest   " . $BFLastSyncTimestamp);
                if (1) {
                    #($timest - $BFLastSyncTimestamp) > 2
                    GetLog->debug("OBJAfterUpdateAddressX- Something can be done" );
                               # $CurrentAddress->set({'BFLastSyncTimestamp' => $timest});
                                #DO THE UPDATE 
                                
                                my $AddressType = $CurrentAddress->get('Alias');
                                my $User        = $CurrentAddress->get('Parent')->get('Parent');
                                my $Customers   = $User->get('Customers');
                                #Bibliophile we will have always customer user relation 1:1
                                
                                if (defined($Customers->[0])) {
                                    GetLog->debug("OBJAfterUpdateAddressX- Customer defined");
						my $ShopperID = "";
                                                $ShopperID = $Customers->[0]->get('OptionsShopperID');
						my $CustomerNumber = 0;
                                                $CustomerNumber  = $Customers->[0]->get('OptionsCustId');
                #TODO: PROTECT AGAINST UNDEFINED SHOPPER ID
                                                #ShopperID = 23094
                                                GetLog->debug("ShopperID: $ShopperID CustomerNumber: $CustomerNumber");
						if ($CustomerNumber eq '') {
						     $CustomerNumber = 0;
						     GetLog->debug("CustomerNumber: $CustomerNumber");
						}

                                                if ($ShopperID eq '') {
                                                     GetLog->debug("AfterUpdateAddress - The user hasn't proper ShopperID - cant be synchronized. " . $User->get('ID'));           
                                                } else {
                                                                my %UserSearchRequest = (
                                                                                        'CustomerNumber'        => $CustomerNumber,
                                                                                        'ShopperID'             => $ShopperID,
                                                                                        'GetAllCustomers'       => 'false',
                                                                                        );
                                                                my $WSLinkGet = Options::Attributes::API::InterfaceCustomerGet::new("Options::Attributes::API::InterfaceCustomerGet",
                                                                                                                           "CustomerSearch",
                                                                                                                           "CustomerSearchRequest",
                                                                                                                            \%UserSearchRequest,
                                                                                                                           "Customer");
                                                                my $Customer = $WSLinkGet->hitMe();
                                                                GetLog->debug("OBJAfterUpdateAddressX - CustomerFromOptions: \n" . Dumper($Customer));
                                                #HERE IS THE PLACE WHERE WE UPDATE HASH
                                                                my $FieldsConverter = new Options::UserSync::API::AddressFieldsConverter();
                                                                if($AddressType =~ m/BillingAddress/) {
                                                                   $FieldsConverter->convertToOptions($CurrentAddress, $Customer, "billing");
								                                   $Customer->{'Modified'} = "true";
                                                                } else {
                                                                   $FieldsConverter->convertToOptions($CurrentAddress, $Customer, "shipping");
                                                                   $Customer->{'Modified'} = "true";
                                                                }
                                                #HERE IS THE PLACE WHERE WE UPDATE HASH
                                                                $Customer->{'Type'} = "7";
                                                                GetLog->debug("OBJAfterUpdateAddressX - CustomerUpdateReq: " . Dumper($Customer));
                                                                my $WSLinkUpdate = Options::Attributes::API::InterfaceCustomerUpdate::new("Options::Attributes::API::InterfaceCustomerUpdate",
                                                                                                                           "CustomerUpdate",
                                                                                                                           "CustomerUpdateRequest",
                                                                                                                            $Customer,
                                                                                                                            "");
                                                                my $Result = $WSLinkUpdate->hitMe();
                                                                # update address
                                                                # sent back user record
                                                                
                                                                GetLog->debug("DO OP Time OK  :\n : " . Dumper($Result));
#Joke:
#Q: There should be string in respond to know that everything is ok after update but it is not there?!
#A: Options doesn't support it yet.

#Q: I can update now the customer record but the CustomerAdditionalAddress still remains unchanged.
#   Can you give me a hint why is that?
#A: Normally, additional addresses are only updated/added as part of an order submission rather than
#   just as a customer update (i.e. a registration only transaction).
#   Remember, that an order submission can do a customer address (main address and/or additional address)
#   add/update at the same time, and, in practice, this is what typically happens.
#
#   That said, you should still be able to add additional addresses via just a customer registration only transaction.
#   Therefore, I'll double check the program to ensure this is the case.
                                                                
                                                }
                                } else {
                                       GetLog->debug("AfterUpdateAddress - The Customer is not defined - cant be synchronized. " . $User->get('ID'));           
                                }
                } else {
                }
                
                }
                #print Dumper($LineItem->get('ObjectID');
        #        }
}

# This scenarios must be covered so far we got only first:
# 
#[2011/01/21 15:04:41] ERROR 192.168.100.114:10047 PID:20349 Category:Options.UserSync.API.UserDataUpdate.OBJAfterUpdateAddress STORE:Store Line:21
#OBJAfterUpdateAddress - TRIGERED/Shops/Bibliophile/Customers/16317/Addresses/BillingAddress
#
#[2011/01/21 15:04:41] ERROR 192.168.100.114:10047 PID:20349 Category:Options.UserSync.API.UserDataUpdate.OBJAfterUpdateAddress STORE:Store Line:21
#OBJAfterUpdateAddress - TRIGERED/Shops/Bibliophile/Users/frogball/Addresses/BillingAddress


1;
